package com.aidex.framework.websocket;

import java.util.concurrent.Semaphore;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import com.aidex.common.utils.SecurityUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.Data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

/**
 * websocket 消息处理
 * 
 * @author ruoyi
 */
@Data
@Component
@ServerEndpoint("/websocket/{type}/{userId}")
public class WebSocketServer
{
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 200;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    // getter setter
    private Session session;

    private String userId;


    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("type") String type,@PathParam("userId") String userId, Session session) throws Exception
    {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag)
        {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, "当前在线人数超过限制数：" + socketMaxOnlineCount);
            session.close();
        }
        else
        {
            this.session=session;
            this.userId=type+userId;
            // 添加用户
            WebSocketUsers.put(type+userId, session);
            LOGGER.info("\n 建立连接 - {}", session);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());
//            if("app".equals(WebSocketUsers.TYPE_APP)){
//                JSONObject jsonObject=new JSONObject();
//                jsonObject.put("type","onLine");
//                jsonObject.put("msg", "APP上线了");
//                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_APP,userId, jsonObject.toJSONString());
//                WebSocketUsers.sendMessageToUserByText(WebSocketUsers.TYPE_PC,userId, jsonObject.toJSONString());
//            }
           // WebSocketUsers.sendMessageToUserByText(session, "连接成功,"+userId);
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(@PathParam("type") String type,@PathParam("userId") String userId, Session session)
    {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(type+userId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(@PathParam("type") String type,@PathParam("userId")String userId, Session session, Throwable exception) throws Exception
    {
        if (session.isOpen())
        {
            // 关闭连接
            session.close();
        }
        LOGGER.info("\n 连接异常 - {}", type+userId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(type+userId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public  void onMessage(String message,Session session)
    {
        session=WebSocketUsers.getUsers().get(userId);
        JSONObject jsonObject=JSONObject.parseObject(message);
        if("ping".equals(jsonObject.getString("type"))){
            jsonObject.put("type","pong");
            jsonObject.put("msg", "pong");
            WebSocketUsers.sendMessageToUserByText(session, jsonObject.toJSONString());
        }else{
            WebSocketUsers.sendMessageToUserByText(session, message);
        }

    }
}
